﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using WSS.BLL.Resource;
using WSS.Models.Res;
using WSS.Pub;

namespace WSS.Web.Controllers
{
    public class ResCenterController : MyController
    {
        //
        // GET: /ResCenter/

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [MyAuthorize]
        public ActionResult List()
        {
            var param = new StrObjDict();

            param.Merger(new { ORDER_BY_CLAUSE = "ORDER_NO,RES_NAME", UPLOADER = AccountCache.UserId });

            string resname = Request.Req("resname"),
                cateno = Request.Req("cateno"),
                whereclause = " 1=1 ";

            if (!resname.IsNullOrEmpty())
            {
                whereclause += " AND RES_NAME LIKE '%" + resname + "%' ";
            }

            if (!string.IsNullOrEmpty(cateno))
            {

                var listnos = new List<string> { cateno };

                get_res_cateno_children(ref listnos, cateno,
                    ResCateDb.Instance.GetList(new { USER_ID = AccountCache.UserId, FLAG_INVALID = 0 }));


                whereclause += " AND ( ";
                foreach (string cate in listnos)
                {
                    whereclause += " CATE_NO = '" + cate + "' OR";
                }
                whereclause = whereclause.TrimEnd('R').TrimEnd('O');
                whereclause += " ) ";

            }

            param.Merger(new { WHERE_CLAUSE = whereclause });

            return this.MyJson(Paginator.Page<Models.Res.RES_RESOURCE>(BLL.Resource.ResDb.Instance.GetList(param)));
        }


        [MyAuthorize]
        public ActionResult Detail(string id)
        {
            string swf = string.Format("/swf/{0}.swf", id);

            if (!System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(swf)))
            {
                // below remember add keywords "return"
                return RedirectToAction("Convert", new { id = id });
            }

            var m = ResDb.Instance.GetOne(id);
            if (m != null)
            {
                m.TOTAL_READ = m.TOTAL_READ + 1;
                ResDb.Instance.Update(m);
            }


            ViewBag.DISPLAY_SWF = swf;

            return View();
        }

        public ActionResult Convert(string id)
        {
            RES_RESOURCE model = ResDb.Instance.GetOne(id);

            ViewData.Model = model;

            return View();
        }

        public ActionResult ResChart()
        {
            var labels = new List<string>();
            var values = new List<int>();

            string sql = @"SELECT count(1) val,to_char(upload_time,'yyyy-MM') txt FROM RES_RESOURCE 
WHERE upload_time BETWEEN ADD_MONTHS(sysdate, -12) AND sysdate AND UPLOADER = '{0}'
GROUP BY to_char(upload_time,'yyyy-MM')";
            sql = string.Format(sql, AccountCache.UserId);

            var list = DB.Select(sql);

            var today = DateTime.Now;
            for (DateTime dt = DateTime.Now.AddYears(-1); dt <= today; dt = dt.AddMonths(1))
            {
                var lbl = dt.ToString("yyyy-MM");
                labels.Add(lbl);
                var temp = list.FirstOrDefault(t => Utils.GetString(t["TXT"]) == lbl);
                if (temp != null && !Utils.GetString(temp, "TXT").IsNullOrEmpty())
                {
                    values.Add(int.Parse(Utils.GetString(temp, "VAL")));
                }
                else
                {
                    values.Add(0);
                }
            }

            ViewBag.CHART_LABELS = labels.ToJson();
            ViewBag.CHART_VALUES = values.ToJson();

            return View();
        }

        [MyAuthorize]
        public ActionResult Upload()
        {
            return View();
        }
        /// <summary>
        /// 在线转换按钮事件
        /// </summary>
        /// <returns></returns>
        public ActionResult OnlineConvert(string id)
        {
            RES_RESOURCE model = ResDb.Instance.GetOne(id);

            BaseRes base_res = new BaseRes();
            base_res.MODEL_RES_RESOURCE = model;
            base_res.MainHttpContext = System.Web.HttpContext.Current;

            string extension_name = model.ORIG_FILE_NAME.Substring(model.ORIG_FILE_NAME.LastIndexOf("."));

            extension_name = extension_name.ToUpper();

            if (extension_name == ".PDF")
            {
                base_res.ResourceCate = EResourceCategory.Pdf;
            }
            else if (extension_name == ".DOC" || extension_name == ".DOCX")
            {
                base_res.ResourceCate = EResourceCategory.Word;
            }

            FileConversionThread t = new FileConversionThread(base_res);
            if (t.IsConvertSuccess)
            {
                return this.MyJson(true, "转换成功");
            }
            else
            {
                return this.MyJson(false, t.Msg);
            }
        }


        [MyAuthorize]
        public ActionResult Category()
        {
            return View();
        }

        [MyAuthorize]
        public ActionResult Document()
        {
            BLL.Resource.ResCenter rec = new BLL.Resource.ResCenter();
            var list = ResCateDb.Instance.GetList(new { INVALID = 0, USER_ID = AccountCache.UserId });
            string s = rec.GetResCategoryGridFormatterValue(list);
            ViewBag.FORMATERVALE_RESCATE = "var fmtcode = " + s + ";";
            return View();
        }
        [MyAuthorize]
        public ActionResult Video()
        {
            return View();
        }

        [MyAuthorize]
        public ActionResult SetResOpt(string id)
        {
            ViewBag.ResNo = id;
            //获取当前文档已有的权限信息
            IList<StrObjDict> OptTypeData = new List<StrObjDict>();

            OptTypeData = DB.ListSod("LIST2_RES_PERMISSION_SET", new { RES_NO = id });


            string OptTypes = "";
            foreach (var data in OptTypeData)
            {
                OptTypes += data["PER_TYPE"] + ",";
            }
            ViewBag.OptTypes = OptTypes != "" ? OptTypes.Substring(0, OptTypes.Length - 1) : "";
            return View();
        }

        [MyAuthorize]
        public ActionResult UsersList(string id)
        {
            ViewBag.ResNo = id;
            //获取当前文档已有的权限信息
            string UserOptSqlStr = "select user_user.user_id val, user_name text from res_permission,user_user  " +
                                   "where res_permission.user_id=user_user.user_id and res_no='" + id + "'";
            ViewBag.UserOptData = DB.Select(UserOptSqlStr);
            return View();
        }

        /// <summary>
        /// 保存当前文档权限
        /// </summary>
        /// <param name="resno"></param>
        /// <param name="opttype"></param>
        /// <param name="optuserdata"></param>
        /// <param name="opthospdata"></param>
        /// <returns></returns>
        [MyAuthorize]
        public JsonResult SaveResOpt(string resno, string opttype, string optuserdata, string opthospdata)
        {
            List<DBState> states = new List<DBState>();
            //删除该资源已有的权限信息
            states.Add(new DBState { Name = "DELETE_RES_PERMISSION_SET2", Param = new { RES_NO = resno }.ToStrObjDict(), Type = ESqlType.DELETE });
            states.Add(new DBState { Name = "DELETE_RES_PERMISSION2", Param = new { RES_NO = resno }.ToStrObjDict(), Type = ESqlType.DELETE });


            //新增该资源的权限信息
            var OptTypeArr = opttype.Split(',');
            var OptUserDataArr = optuserdata.Split(',');
            var OptHospDataArr = opthospdata.Split(',');

            foreach (var optType in OptTypeArr)
            {
                if (optType == "HOSPITAL")
                {
                    foreach (var resHospOpt in OptHospDataArr)
                    {
                        RES_PERMISSION_SET resPermissionHosp = new RES_PERMISSION_SET();
                        resPermissionHosp.PK_ID = BLL.Xt.XhbManager.Instance.GetXh("RES_PERMISSION_SET");
                        resPermissionHosp.RES_NO = resno;
                        resPermissionHosp.PER_TYPE = optType;
                        resPermissionHosp.PER_DESC = resHospOpt;
                        states.Add(new DBState
                        {
                            Name = resPermissionHosp.MAP_INSERT,
                            Param = resPermissionHosp.ToDict(),
                            Type = ESqlType.INSERT
                        });
                    }
                }
                else
                {
                    RES_PERMISSION_SET resPermissionSet = new RES_PERMISSION_SET();
                    resPermissionSet.PK_ID = BLL.Xt.XhbManager.Instance.GetXh("RES_PERMISSION_SET");
                    resPermissionSet.RES_NO = resno;
                    resPermissionSet.PER_TYPE = optType;
                    resPermissionSet.PER_DESC = optType;
                    if (optType == "PERSON")
                    {
                        //指定用户
                        foreach (var resUserOpt in OptUserDataArr)
                        {
                            RES_PERMISSION resPermission = new RES_PERMISSION();
                            resPermission.RES_NO = resno;
                            resPermission.USER_ID = resUserOpt;
                            states.Add(new DBState { Name = resPermission.MAP_INSERT, Param = resPermission.ToDict(), Type = ESqlType.INSERT });
                        }
                    }
                    states.Add(new DBState
                    {
                        Name = resPermissionSet.MAP_INSERT,
                        Param = resPermissionSet.ToDict(),
                        Type = ESqlType.INSERT
                    });
                }
            }
            DB.Execute(states);
            return this.MyJson(true, "文档权限设置成功！");
        }

        [MyAuthorize]
        public ActionResult HospList(string id)
        {
            string HospOptSqlStr = "select hosp_name text, hosp_id val from hosp_hospital where hosp_id in  " +
                                   "(select PER_DESC from RES_PERMISSION_SET where PER_TYPE='HOSPITAL' and RES_NO='" + id + "')";
            ViewBag.HospOptData = DB.Select(HospOptSqlStr);
            ViewBag.ResNo = id;
            return View();
        }

        /// <summary>
        /// 依据文档编号，获取有该文档权限的用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [MyAuthorize]
        public ActionResult OptUserList(string id)
        {
            string SqlStr = @"select user_user.*,res_no from user_user left join res_permission
                              on user_user.user_id =res_permission.user_id
                              and res_no='" + id + "' where hosp_id='" + AccountCache.CurrentUserInfo.UserInfo.HOSP_ID + "'";
            var username = Request.Req("username");
            if (!username.IsNullOrEmpty())
            {
                SqlStr += " and USER_NAME LIKE '%" + username + "%'";
            }
            SqlStr += " order by user_user.USER_ID DESC";
            return this.MyJson(Paginator.Page<StrObjDict>(DB.Select(SqlStr)));
        }
        /// <summary>
        /// 依据文档编号，获取有该文档权限的医院
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [MyAuthorize]
        public ActionResult OptHospList(string id)
        {
            string SqlStr = @"select hosp_name, hosp_id,res_no from hosp_hospital left join res_permission_set
                             on hosp_hospital.hosp_id =res_permission_set.per_desc
                             and  per_type='HOSPITAL' and res_no='" + id + "'";
            var hospname = Request.Req("sch_hospname");
            if (!hospname.IsNullOrEmpty())
            {
                SqlStr += " where  hosp_name LIKE '%" + hospname + "%'";
            }
            SqlStr += " order by hosp_id DESC";
            return this.MyJson(Paginator.Page<StrObjDict>(DB.Select(SqlStr)));
        }


        #region 资源分类

        public ActionResult GetResCategoryBtnMenu()
        {
            var list = BLL.Resource.ResCateDb.Instance.GetList(new { USER_ID = AccountCache.UserId, FALG_INVALID = 0, ORDER_BY_CLAUSE = "CATE_LEVEL,ORDER_NO" });
            StringBuilder html = new StringBuilder();

            if (list.Count > 0)
            {
                if (Request.Req("selectall") == "1")
                {
                    html.AppendLine("<li><a href=\"#\" onclick='on_rescate_menu_click(\"\",\"全部\")'>选择全部</a></li>");
                    html.AppendLine("<li class=\"divider\"></li>");
                }
                get_res_cate_button_menu(ref html, "ROOT", list);
            }
            else
            {
                html.AppendLine("<li><a href=\"/rescenter/category\">您没有设置分类，现在设置</a></li>");
            }
            return Content(html.ToString());
        }

        public ActionResult AddCategory()
        {


            var order = Request.Req("orderno");
            var catename = Request.Req("catename");
            var parentno = Request.Req("parentno");
            var level = Request.Req("level");

            if (catename.IsNullOrEmpty() || parentno.IsNullOrEmpty() || order.IsNullOrEmpty())
            {
                return this.MyJson(false, "分类新增失败，缺少参数");
            }

            var listdb = new List<DBState>();

            RES_CATEGORY model = new RES_CATEGORY();
            model.CATE_NAME = Request.Req("catename");
            model.ORDER_NO = order.IsNumeric() ? int.Parse(order) : 12;
            model.CATE_PNO = parentno;
            model.FLAG_INVALID = 0;
            model.CATE_NO = BLL.Xt.XhbManager.Instance.GetXh(model.GetTableName());
            model.USER_ID = AccountCache.UserId;
            model.FLAG_LAST = 1;
            model.CATE_LEVEL = int.Parse(level);

            if (model.CATE_PNO != "ROOT")
            {
                RES_CATEGORY parentmodel = ResCateDb.Instance.GetOne(model.CATE_PNO);
                parentmodel.FLAG_LAST = 0;
                listdb.Add(new DBState { Name = parentmodel.MAP_UPDATE, Param = parentmodel, Type = ESqlType.UPDATE });
            }
            listdb.Add(new DBState { Name = model.MAP_INSERT, Param = model, Type = ESqlType.INSERT });
            DB.Execute(listdb);

            return this.MyJson(true, model.CATE_NO);
        }

        public ActionResult RenameCateName()
        {
            string cateno = Request.Req("cateno"),
                newname = Request.Req("newname");

            try
            {
                var dbinstance = BLL.Resource.ResCateDb.Instance;
                var model = dbinstance.GetOne(cateno);
                model.CATE_NAME = newname;
                dbinstance.Update(model);
                return this.MyJson(true, "分类重命名成功");
            }
            catch (Exception ex)
            {
                return this.MyJson(false, "分类重命名失败");
            }
        }

        public ActionResult RemoveCate()
        {
            string cateno = Request.Req("cateno");

            try
            {
                var dbinstance = BLL.Resource.ResCateDb.Instance;
                var userid = AccountCache.UserId;

                var model = dbinstance.GetOne(cateno);

                if (model == null || model.CATE_NO == null)
                {
                    return this.MyJson(false, "分类不存在，刷新页面后再看看吧");
                }

                if (model.USER_ID != userid)
                {
                    return this.MyJson(false, "大哥，你删错对象了，别乱改参数啊");
                }

                if (model.FLAG_LAST == 0)
                {
                    return this.MyJson(false, "只能移除末级的分类");
                }

                var listres = ResDb.Instance.GetList(new { CATE_NO = cateno });
                if (listres.Count > 0)
                {
                    return this.MyJson(false, "该分类下有" + listres.Count + "项资源文件，不允许删除!");
                }

                var listdb = new List<DBState>();

                if (model.CATE_PNO != "ROOT")
                {
                    var siblings = dbinstance.GetList(new { CATE_NO = model.CATE_PNO, FLAG_INVALID = 0, USER_ID = userid });
                    if (siblings.Count == 1)
                    {
                        var paentmodel = dbinstance.GetOne(model.CATE_PNO);
                        paentmodel.FLAG_LAST = 1;
                        listdb.Add(new DBState { Name = paentmodel.MAP_UPDATE, Param = paentmodel, Type = ESqlType.UPDATE });
                    }
                }
                listdb.Add(new DBState { Name = model.MAP_DELETE, Param = model, Type = ESqlType.DELETE });

                DB.Execute(listdb);

                return this.MyJson(true, "分类移除成功");
            }
            catch (Exception ex)
            {
                return this.MyJson(false, "分类移除失败");
            }
        }


        public ContentResult GetResCateGrid()
        {
            var list = BLL.Resource.ResCateDb.Instance.GetList(new { USER_ID = AccountCache.UserId, ORDER_BY_CLAUSE = "CATE_LEVEL,ORDER_NO" });
            StringBuilder html = new StringBuilder();
            if (list.Count > 0)
            {
                get_res_cate_grid(ref html, "ROOT", list);
            }
            return Content(html.ToString());
        }

        /// <summary>
        /// 前端管理分类需要
        /// </summary>
        /// <param name="html"></param>
        /// <param name="parentno"></param>
        /// <param name="datas"></param>
        private void get_res_cate_grid(ref StringBuilder html, string parentno, IEnumerable<RES_CATEGORY> datas)
        {
            var subdatas = datas.Where(t => t.CATE_PNO == parentno).ToList();

            foreach (RES_CATEGORY category in subdatas)
            {
                html.AppendLine("<li class=\"list-group-item\" style=\"margin-left:" + category.CATE_LEVEL * 50 + "px;\" data-cateno=\"" + category.CATE_NO + "\" data-lvl=\"" + category.CATE_LEVEL + "\">");
                html.AppendLine("<label>" + category.CATE_NAME + "</label>");
                html.AppendLine("<span class=\"pull-right close\" onclick=\"removecate(this);\">&times;</span >");
                html.AppendLine("</li>");

                if (category.FLAG_LAST != 1)
                {
                    get_res_cate_grid(ref html, category.CATE_NO, datas);
                }
            }
        }

        /// <summary>
        /// 前端按钮下拉菜单需要
        /// </summary>
        /// <param name="html"></param>
        /// <param name="parentno"></param>
        /// <param name="datas"></param>
        private void get_res_cate_button_menu(ref StringBuilder html, string parentno, IEnumerable<RES_CATEGORY> datas)
        {
            var subdatas = datas.Where(t => t.CATE_PNO == parentno);

            foreach (RES_CATEGORY category in subdatas)
            {
                html.AppendLine("<li data-cateno='" + category.CATE_NO + "'>");
                html.AppendLine("<a href='#' style='margin-left:" + category.CATE_LEVEL * 10 + "px;' onclick='on_rescate_menu_click(\"" + category.CATE_NO + "\",\"" + category.CATE_NAME + "\")'>" + category.CATE_NAME + "</a>");
                html.AppendLine("</li>");

                if (category.FLAG_LAST != 1)
                {
                    get_res_cate_button_menu(ref html, category.CATE_NO, datas);
                }
            }
        }

        /// <summary>
        /// 递归取得所有的子分类编号
        /// </summary>
        /// <param name="listnos"></param>
        /// <param name="parentno"></param>
        /// <param name="datas"></param>
        private void get_res_cateno_children(ref List<string> listnos, string parentno, IEnumerable<RES_CATEGORY> datas)
        {
            var subdatas = datas.Where(t => t.CATE_PNO == parentno);

            foreach (RES_CATEGORY category in subdatas)
            {
                listnos.Add(category.CATE_NO);

                if (category.FLAG_LAST != 1)
                {
                    get_res_cateno_children(ref listnos, category.CATE_NO, datas);
                }
            }
        }

        #endregion

    }
}
